/*
 * To do:
 * global shortcut - win32
 * popup reminder on top of all windows - win 32
 * keyboard shortcut for certain view
 * converting Upcoming and output results into TABLEviewer
 * smarter Digestion of typed stuff, mapping "tmr or tomorrow" to correct day, completion of keywords
 * Calendar and no of tasks underneath calendar
 * 
 */


package GUI;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;

import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Label;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Slider;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Listener;

import dennis.CommandInput;
import dennis.Task;

import java.awt.event.ActionListener;
import java.lang.String;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.widgets.Table;
import org.eclipse.jface.viewers.TableViewer;




public class GUI extends Composite {

	private final FormToolkit toolkit = new FormToolkit(Display.getCurrent());
	private Text inputCmdBox;
	private Text displayBox;
	private Label cmdHints;
	//used by ListViever
	private List dialogList = null; 
	private ArrayList<String> outputGUI = null; 
	//used by side panel
	private List sidePanelList = null; 
	//used by Tabler
	
	private java.util.ArrayList<Task> viewListGUIcopied; 
	private java.util.ArrayList<Task> viewListGUI;
	private TaskComparator comparator;
	private Table table;
	
	
	

	public GUI(Composite parent, int style) {
		super(parent, SWT.BORDER);
		final Shell shell = parent.getShell();
		final Display display = parent.getDisplay();
		CommandInput.initInput();
		
		//sample tasks
		CommandInput.staticInput.AddTask(new Task(03, 05, 12, "0800", "1000", "", false, "run 15 May 8am-10am", "bishanpark"));
		CommandInput.staticInput.AddTask(new Task(05, 11, 12, "1900", "2000", "Faith", true, "mybirthday at church", "church"));
		CommandInput.staticInput.parseCmd("+* #160512 @1000-1200 :Study CS2103 exam $NUS");
		CommandInput.staticInput.parseCmd("+* #160512 @1000-1200 CS2103 exam no label $NUS");
		
		CommandInput.staticInput.parseCmd("view all");
		viewListGUI = CommandInput.staticInput.outTable();
		outputGUI = CommandInput.staticInput.out();
		outputGUI.clear();
		
		//viewListGUIcopied = new ArrayList(output);
		  
		
		shell.setText("Remember4Me - v0.1");
		Color blue = display.getSystemColor(SWT.COLOR_WHITE);
		setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
		setSize(new Point(815, 441));
		addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				toolkit.dispose();
			}
		});
		
		//toolkit.adapt(this);
		//toolkit.paintBordersFor(this);
		toolkit.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		setLayout(null);
		
		/*Menu Bar
		 * 
		 */
		final Menu mbar = new Menu(shell,SWT.BAR );
        
        // create a File menu and add an Exit item
        final MenuItem file = new MenuItem(mbar, SWT.CASCADE);
        file.setText("&File");
        final Menu filemenu = new Menu(shell, SWT.DROP_DOWN);
        file.setMenu(filemenu);
        final MenuItem openItem = new MenuItem(filemenu, SWT.PUSH);
        openItem.setText("&Open");
        final MenuItem item03 = new MenuItem(filemenu, SWT.PUSH);
        item03.setText("&Save to File\tCTRL+S");
        item03.setAccelerator(SWT.CTRL+'S');
        item03.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                //System.out.println("perform view actions");
            	dialogList.removeAll();
            	dialogList.add("Successfully Saved");
              }
            });
        final MenuItem separator = new MenuItem(filemenu, SWT.SEPARATOR);
        final MenuItem exitItem = new MenuItem(filemenu, SWT.PUSH);
        exitItem.setText("E&xit");
        exitItem.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
            	shell.dispose();
            }
        });
        
        
        //create a Window menu and add Child items
        final MenuItem view = new MenuItem(mbar, SWT.CASCADE);
        view.setText("&View");
        final Menu viewmenu = new Menu(shell, SWT.DROP_DOWN);
        view.setMenu(viewmenu);
        final MenuItem item01 = new MenuItem(viewmenu, SWT.PUSH);
        item01.setText("by&Date\tCTRL+1");
        item01.setAccelerator(SWT.CTRL+'1');
        item01.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                //System.out.println("perform view actions");
            	inputCmdBox.setText("+date");
            	inputCmdBox.selectAll();
            	doPrint();
            	doUpdateTable();
            	//outputList.setFocus();
              }
            });
        final MenuItem item02 = new MenuItem(viewmenu, SWT.PUSH);
        item02.setText("&Next10\tCTRL+2");
        item02.setAccelerator(SWT.CTRL+'2');
        item02.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                //System.out.println("perform view actions");
            	//inputCmdBox.setText("overdue");
            	sidePanelList.removeAll();
            	ArrayList<String> output = null;
            	output = CommandInput.staticInput.upcomingTen();
        		int size = output.size();
        		for(int i = 0; i < size ; i++){
        			//System.out.println(size);
        			String astr = output.get(i);
        			//displayBox.append(astr + "\n");
        			sidePanelList.add(astr);
        		}
        		output.clear();
              }
            });
    
        shell.setMenuBar(mbar);
		
		/* User input Box
		 * 
		 */
		inputCmdBox = new Text(this, SWT.BORDER);
		inputCmdBox.setBounds(115, 95, 464, 25);
		inputCmdBox.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				inputBoxkeyReleased(e);
			}
		});
		
		inputCmdBox.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent e) {
				//inputCmdBox.setText("");
			}
		});
		
		inputCmdBox.setText("What can I do for you? =)");
		inputCmdBox.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL));
		toolkit.adapt(inputCmdBox, true, true);
		
		/*Command Label
		 * 
		 */
		Label inputCmdLabel = new Label(this, SWT.NONE);
		inputCmdLabel.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
		inputCmdLabel.setForeground(SWTResourceManager.getColor(255, 255, 255));
		//inputCmdLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL));
		inputCmdLabel.setBounds(30, 99, 79, 18);
		//toolkit.adapt(inputCmdLabel, true, true);
		inputCmdLabel.setText("Command:");
		
		/*Output Display Box
		 * 
		 */
		/*
		displayBox = new Text(this, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL);
		displayBox.setEditable(false);
		displayBox.setBounds(30, 96, 514, 325);
		toolkit.adapt(displayBox, true, true);
		*/
		ListViewer displayBox = new ListViewer(this, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
		dialogList = displayBox.getList();
		//outputList.setFont(SWTResourceManager.getFont("Lucida Grande", 14, SWT.NORMAL));
		dialogList.setBounds(231, 10, 348, 79);
		toolkit.adapt(dialogList, true, true);
		
		dialogList.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				int index;
				//System.out.println(e.keyCode);
				if(127 == e.keyCode) { //delete  - remove task  
					index = dialogList.getSelectionIndex();
					if(index >= 0){
						System.out.println(index);
						dialogList.remove(index);
						if(index >= 1) index--;
						dialogList.select(index);
					}
				}
				if(32 == e.keyCode) { //space bar - continue modification
					inputCmdBox.setFocus();
					inputCmdBox.append(" ");
				}
				if(27 == e.keyCode) { //ESC key - start over
					inputCmdBox.setFocus();
				}
				if(e.stateMask == SWT.CTRL && 100 == e.keyCode) { //D key - done task  <<<<<
					index = dialogList.getSelectionIndex();
					if(index >= 0){
						System.out.println(index);
						String oldstr = dialogList.getItem(index);
						String newstr = "DONE! > "+oldstr;
						dialogList.remove(index);
						dialogList.add(newstr, index);
						dialogList.select(index);
						//inputCmdBox.setFocus();
					}
				}
			}
		});
		
		dialogList.addSelectionListener(new SelectionListener() {
			public void widgetSelected(SelectionEvent e) {
				//int[] indices = outputList.getSelectionIndices();
				String[] items = dialogList.getSelection();
				int id = dialogList.getSelectionIndex() + 1;
				StringBuffer buffer = new StringBuffer(" ");
				buffer.append(items[0]);
				//
				//System.out.println(buffer.toString());
				inputCmdBox.setText("mod "+"id:"+id);
				//inputCmdBox.setFocus();
			}

			public void widgetDefaultSelected(SelectionEvent e) {
				widgetSelected(e);
			}
		});
		
		/*Output Display Table
		 * 
		 
		table_1 = new Table(this, SWT.BORDER | SWT.FULL_SELECTION);
		table_1.setBounds(28, 187, 514, 213);
		toolkit.adapt(table_1);
		toolkit.paintBordersFor(table_1);
		table_1.setHeaderVisible(true);
		table_1.setLinesVisible(true);
		
		TableColumn tblclmnNewColumn = new TableColumn(table_1, SWT.NONE);
		tblclmnNewColumn.setWidth(100);
		tblclmnNewColumn.setText("New Column");
		
		TableColumn tblclmnPpp = new TableColumn(table_1, SWT.NONE);
		tblclmnPpp.setWidth(100);
		tblclmnPpp.setText("ppp");
		*/
		
		comparator = new TaskComparator();
		comparator.setColumn(TaskComparator.DATE);
		comparator.setDirection(TaskComparator.ASCENDING);
		 // Create the table
	    table = new Table(this, SWT.BORDER);
	    table.setBounds(28, 153, 551, 268);
	    toolkit.adapt(table);
		toolkit.paintBordersFor(table);
	    table.setHeaderVisible(true);
	    table.setLinesVisible(true);

	    // Add a Listener to track current selected item in table
	    table.addSelectionListener(new SelectionAdapter() {
	        public void widgetSelected(SelectionEvent event) {
	          //System.out.println(table.getSelectionIndex());
	        	int id = table.getSelectionIndex();
	        	int displayID =  id + 1;
					Task selectedTask = viewListGUI.get(id); // if id not correct can cause program crash
					String selectedTaskstr = selectedTask.printTask_addIdentifier();
					inputCmdBox.setText("mod "+displayID+" +"+selectedTaskstr);
				//inputCmdBox.setFocus();
	        }
	      });
	    
	    // Create each of the columns, adding an event
	    // listener that will set the appropriate fields
	    // into the comparator and then call the fillTable
	    // helper method
	    TableColumn[] columns = new TableColumn[8];
	    columns[0] = new TableColumn(table, SWT.NONE);
	    columns[0].setText("No.");
	    
	    columns[1] = new TableColumn(table, SWT.NONE);
	    columns[1].setText("Impt");
	    columns[1].addSelectionListener(new SelectionAdapter() {
	      public void widgetSelected(SelectionEvent event) {
	        comparator.setColumn(TaskComparator.IMPORTANCE);
	        comparator.reverseDirection();
	        fillTable(table);
	      }
	    });
	    
	    columns[2] = new TableColumn(table, SWT.NONE);
	    columns[2].setText("Date");
	    columns[2].addSelectionListener(new SelectionAdapter() {
	      public void widgetSelected(SelectionEvent event) {
	        comparator.setColumn(TaskComparator.DATE);
	        comparator.reverseDirection();
	        fillTable(table);
	      }
	    });

	    columns[3] = new TableColumn(table, SWT.NONE);
	    columns[3].setText("Start");
	    columns[3].addSelectionListener(new SelectionAdapter() {
	      public void widgetSelected(SelectionEvent event) {
	        comparator.setColumn(TaskComparator.START);
	        comparator.reverseDirection();
	        fillTable(table);
	      }
	    });
	    
	    columns[4] = new TableColumn(table, SWT.NONE);
	    columns[4].setText("End");
	    columns[4].addSelectionListener(new SelectionAdapter() {
	      public void widgetSelected(SelectionEvent event) {
	        comparator.setColumn(TaskComparator.END);
	        comparator.reverseDirection();
	        fillTable(table);
	      }
	    });

	    columns[5] = new TableColumn(table, SWT.NONE);
	    columns[5].setText("Description");
	    columns[5].setWidth(150);
	    columns[5].addSelectionListener(new SelectionAdapter() {
	      public void widgetSelected(SelectionEvent event) {
	        comparator.setColumn(TaskComparator.DESCRIPTION);
	        comparator.reverseDirection();
	        fillTable(table);
	      }
	    });
	    
	    columns[6] = new TableColumn(table, SWT.NONE);
	    columns[6].setText("Label");
	    columns[6].addSelectionListener(new SelectionAdapter() {
	      public void widgetSelected(SelectionEvent event) {
	        comparator.setColumn(TaskComparator.LABEL);
	        comparator.reverseDirection();
	        fillTable(table);
	      }
	    });
	    
	    columns[7] = new TableColumn(table, SWT.NONE);
	    columns[7].setText("Venue");
	    columns[7].addSelectionListener(new SelectionAdapter() {
	      public void widgetSelected(SelectionEvent event) {
	        comparator.setColumn(TaskComparator.VENUE);
	        comparator.reverseDirection();
	        fillTable(table);
	      }
	    });
	    
	    // Do the initial fill of the table
	    fillTable(table);

	    // Pack each column so initial display is good
	    for (int i = 0, n = columns.length; i < n; i++) {
	      if(i != 5) columns[i].pack();
	    }
	    
	    
		
		
		
		
		/*Command Input Hints Box
		 * 
		 */
		cmdHints = new Label(this, SWT.NONE);
		cmdHints.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
		cmdHints.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		//cmdHints.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL));
		cmdHints.setBounds(27, 124, 514, 23);
		//toolkit.adapt(cmdHints, true, true);
		
		
		/*Upcoming tasks Box
		 * 
		 */
		Label lblUpcomingTask = new Label(this, SWT.NONE);
		lblUpcomingTask.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
		lblUpcomingTask.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		lblUpcomingTask.setBounds(609, 81, 175, 19);
		//toolkit.adapt(lblUpcomingTask);
		//toolkit.paintBordersFor(lblUpcomingTask);
		lblUpcomingTask.setText("Upcoming Task :");
		
		
		ListViewer listViewer = new ListViewer(this, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
		sidePanelList = listViewer.getList();
		sidePanelList.setForeground(SWTResourceManager.getColor(255, 255, 255));
		sidePanelList.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL));
		sidePanelList.setBounds(609, 109, 175, 158);
		toolkit.adapt(sidePanelList, true, true);
			//list.add("report on........Tmr 3pm     ");
			//list.add("buy gift fo......Thurs         ");
			//list.add("swimming w Jack .02Jun 5-7pm   ");
		setTabList(new Control[]{inputCmdBox, dialogList});
		//setTabList.add("dd");
		
		 
		/*DATE TIME display + Reminder function
		 * 
		 */
		final Label timeLabel = new Label(this, SWT.NONE);
		timeLabel.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
		timeLabel.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		timeLabel.setAlignment(SWT.RIGHT);
		timeLabel.setBounds(599, 0, 206, 14);
		
		
		Image logo = new Image(display, "files/remember4melogo.png");
		Label lblNewLabel = new Label(this, SWT.NONE);
		lblNewLabel.setBounds(10, 27, 198, 40);
		toolkit.adapt(lblNewLabel, true, true);
		lblNewLabel.setImage(logo);
		
		
		//toolkit.adapt(timeLabel, true, true);
		
		//final Display display = parent.getDisplay();
		final DateFormat timeFormat01 = new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss a");
		//final DateFormat timeFormat02 = new SimpleDateFormat("ddMMyyyy"); 
		
		//Start the time checker
		Runnable timer = new Runnable() { 
			public void run() {
				//Set the time/date due from next task, if no next task, then set to year 2099
				Calendar reminder = Calendar.getInstance(); 
				//need NEW func: break nexttask's ddmmyy into int yyyy, int mm, int dd...
				reminder.set(2013, 04, 29, 16, 38); //note jan is zero, dec is 11!
				
				//Get current time details
				Calendar curCal = Calendar.getInstance(); //Date date = new Date();
				Date date = curCal.getTime();
				
				//update GUI timelabel
				String time = timeFormat01.format(date);
				timeLabel.setText(time); 	//System.out.println("timecheck");
				
				boolean overdue = curCal.after(reminder);
				if(overdue) {				//System.out.println("overdue");
					MessageBox messageBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
					//Dialog messageBox = new Da
					messageBox.setText("Reminders");
					messageBox.setMessage("Task description here...");
					int buttonID = messageBox.open();
						switch(buttonID) {
			            case SWT.OK:		// saves changes ...
			            	reminder.set(2019, 04, 28, 15, 40);
						}
					System.out.println(buttonID);
				}
				display.timerExec(1000, this);
			}
		};
		display.timerExec(1000, timer);
		
		//display.syncExec(timer);
		
		
		
	}
	
	/*My functions
	 * 
	 */
	void notifyListeners(int eventType) {
		Event event = new Event();
		event.type = eventType;
		event.widget = this;
		notifyListeners(eventType, event);
	}
	

	private void inputBoxkeyReleased(KeyEvent e) {
		//System.out.println(e.keyCode);
		String userInput = inputCmdBox.getText();
		//System.out.println(userInput);
		String startstr = null;
		String action = null;
		
		if(userInput.length() > 0) {
			startstr = userInput.substring(0,1);
			if(startstr.compareTo("+") == 0) {cmdHints.setText("+(*) <Task details> :<label> #<date> @<time> $<venue>"); action = "add";}
			if(startstr.compareTo("-") == 0) {cmdHints.setText("- id:n"); action = "remove";}
			//if(startch == 'm') cmdHints.setText("mod id:n ...");
			//if(startch == 'd') cmdHints.setText("done id:n ...");
			
			if(userInput.length() > 2){
				startstr = userInput.substring(0,3); //can edit title without typing everything again?
				if(startstr.compareTo("mod") == 0) {cmdHints.setText("mod <id:n> <title> :<label> #<date> @<time> $<venue>"); action = "modify";}	
			}
			if(userInput.length() > 3){
				startstr = userInput.substring(0,4); //how to search within a view? 
				if(startstr.compareTo("view") == 0) {cmdHints.setText("view :<label> | #<date> | @<time> | $<venue>"); action = "view";}	
			}
			if(userInput.length() > 3){
				startstr = userInput.substring(0,4); //can fast done on focused task?
				if(startstr.compareTo("done") == 0) {cmdHints.setText("done <id:n>"); action = "view";}	
			}
			if(userInput.length() > 5){
				startstr = userInput.substring(0,6);
				if(startstr.compareTo("search") == 0) {cmdHints.setText("search ?"); action = "search";}	
			}
			
		} else {
				cmdHints.setText("");
				inputCmdBox.setText("What can I do for you? =)");
				inputCmdBox.selectAll();
		}
		
		//when ENTER is pressed and released
		if(13 == e.keyCode){ 
			if(action != null) {doPrint();doUpdateTable();}
			else{ 
				dialogList.removeAll();
				dialogList.add("Please check your commands");	//doPrintErr();
			}	
		}
		
		if(e.stateMask == SWT.CTRL && e.keyCode == 'a'){     //selectall 
		      inputCmdBox.selectAll();
		    }
		
		if(16777218 == e.keyCode){ //down arrow
			dialogList.setFocus();
		}
	}
	
	public void doPrint(){
		//System.out.println(e.keyCode);
		
		String userInput = inputCmdBox.getText();
		inputCmdBox.selectAll();
		//displayBox.setText("");
		dialogList.removeAll();
		
		CommandInput.staticInput.parseCmd(userInput);
		outputGUI = CommandInput.staticInput.out();
		
		int size = outputGUI.size();
		for(int i = 0; i < size ; i++){
			//System.out.println(size);
			String astr = outputGUI.get(i);
			//displayBox.append(astr + "\n");
			dialogList.add(astr);
		}
		outputGUI.clear();
		//outputList.setFocus();
		dialogList.select(0); 
		
		
		
		
		 /*
		 Parser parser = new Parser(userInput);
		 parser.parseCmd(action);
		
		 output = Parser.out();
		 int size = output.size();
		 for(int i = 0; i < size ; i++){
			 //System.out.println(size);
			 String astr = output.get(i);
			 displayBox.append(astr + "\n");
		 }
		 output.clear();
		 */
	}
	

	public void doUpdateTable(){
		viewListGUI = CommandInput.staticInput.outTable();
		//viewListGUIcopied = new ArrayList(output);
		fillTable(table);
	}

	  /*Updates the Table
	   * 
	   */
	  @SuppressWarnings("unchecked")
	  private void fillTable(Table table) {
	  	  // Turn off drawing to avoid flicker
	  	  table.setRedraw(false);
	  	  
	  	  // We remove all the table entries, sort our rows, then add the entries
	  	  table.removeAll();
	  	  Collections.sort(viewListGUI, comparator);
	  	  System.out.println("From GUI: refreshing table, prints viewListGUI");
	  	  //Iterator<Task> itr2 = viewListGUIcopied.iterator();
	  	  for (Iterator<Task> itr = viewListGUI.iterator(); itr.hasNext();) {
	  	      Task aTask = (Task) itr.next();
	  	      //Task aTaskCopied = (Task) itr2.next();
	  	      System.out.println(aTask.printTask_addIdentifier());
	  	      
	  	      TableItem item = new TableItem(table, SWT.NONE);
	  	      int c = 0;
	  	      String id = Integer.toString(viewListGUI.indexOf(aTask)+1);
	  	      
	  	      
	  	      item.setText(c++, id);
	  	      item.setText(c++, (aTask.hasImportance()) ? "*":"" );
	  	      item.setText(c++, aTask.getDateString("ddmmyy"));
	  	      item.setText(c++, aTask.getstrStartTime());
	  	      item.setText(c++, aTask.getstrEndTime());
	  	      item.setText(c++, aTask.getDescription());
	  	      item.setText(c++, aTask.getLabel());
	  	      item.setText(c++, aTask.getVenue());
	  	  }
	  	  System.out.println("------------");

	  	  // Turn drawing back on
	  	  table.setRedraw(true);
	  }

	  /*
	   * This class does the comparisons for sorting Task objects.
	   */
	  class TaskComparator implements Comparator {
	    /** Constant for column tag */
	    public static final int ID = 0;
	    public static final int IMPORTANCE = 1;
	    public static final int DATE = 2;
	    public static final int START = 3;
	    public static final int END = 4;
	    public static final int DESCRIPTION = 5;
	    public static final int LABEL = 6;
	    public static final int VENUE = 7;
	    
	    /** Constant for direction */
	    public static final int ASCENDING = 0;
	    public static final int DESCENDING = 1;

	    private int column;
	    private int direction;

	    /**
	     * Compares two Playerv2 objects
	     * 
	     * @param obj1 the first Playerv2
	     * @param obj2 the second Playerv2
	     * @return int
	     * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
	     */
	    public int compare(Object obj1, Object obj2) {
	      int rc = 0;
	      Task p1 = (Task) obj1;
	      Task p2 = (Task) obj2;

	      // Determine which field to sort on, then sort on that field
	      switch (column) {
	      case IMPORTANCE:
	    	  String bool1 = "false";
	    	  String bool2 = "false";
	    	  if(p1.hasImportance()) bool1 = "true";
	    	  if(p2.hasImportance()) bool2 = "true";
	      	//rc = p1.hasImportance() == p2.hasImportance() ? -1 : 1;
	    	rc = bool1.compareTo(bool2);
	        break;
	      case DATE:
	        rc = p1.getDateString("yymmdd").compareTo(p2.getDateString("yymmdd"));
	        break;
	      case START:
	        rc = p1.getstrStartTime().compareTo(p2.getstrStartTime());
	        break;
	      case END:
	      	rc = p1.getstrEndTime().compareTo(p2.getstrEndTime());
	        break;
	      case DESCRIPTION:
	        rc = p1.getDescription().compareTo(p2.getDescription());
	        break;
	      case LABEL:
	        rc = p1.getLabel().compareTo(p2.getLabel());
	        break;
	      case VENUE:
	          rc = p1.getVenue().compareTo(p2.getVenue());
	          break;
	      }

	      // Check the direction for sort and flip the sign if appropriate
	      if (direction == DESCENDING) {
	        rc = -rc;
	      }
	      return rc;
	    }

	    /**
	     * Sets the column for sorting
	     * 
	     * @param column the column
	     */
	    public void setColumn(int column) {
	      this.column = column;
	    }

	    /**
	     * Sets the direction for sorting
	     * 
	     * @param direction the direction
	     */
	    public void setDirection(int direction) {
	      this.direction = direction;
	    }

	    /**
	     * Reverses the direction
	     */
	    public void reverseDirection() {
	      direction = 1 - direction;
	    }
	  }
}
